package com.example.computer_exam_training_sys.controller;

import com.example.computer_exam_training_sys.entity.UserFavorite;
import com.example.computer_exam_training_sys.service.UserFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

@RestController
public class UserFavoriteController {

    @Autowired
    private UserFavoriteService favoriteService;

    @PostMapping("/add")
    public String addFavorite(@RequestBody UserFavorite favorite) {
        try {
            favoriteService.addFavorite(favorite);
            return "收藏成功";
        } catch (DuplicateKeyException e) {
            return "该题已收藏";
        } catch (Exception e) {
            return "收藏失败：" + e.getMessage();
        }
    }

    @DeleteMapping("/delete")
    public String deleteFavorite(@RequestBody UserFavorite favorite) {
        try {
            favoriteService.removeFavorite(favorite.getUserId(), favorite.getQuestionId());
            return "取消收藏成功";
        } catch (Exception e) {
            return "取消收藏失败：" + e.getMessage();
        }
    }

    @GetMapping("/check")
    public boolean checkFavorite(@RequestParam int userId, @RequestParam int questionId) {
        return favoriteService.isFavorite(userId, questionId);
    }
}
